package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author jinze
 * @since 2022-08-06
 */
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {

    //频道列表分页查询
    @Override
    public ResponseResult channelListPage(ChannelDto dto) {

        IPage<WmChannel> wmChannelIPage = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        //分页条件，若从前端传过来的频道名为不为空，则添加查询
        if (StringUtils.isEmpty(dto.getName())){
            queryWrapper.like(WmChannel::getName,dto.getName());
        }
        IPage<WmChannel> page = this.page(wmChannelIPage, queryWrapper);
        //返回通用分页页面
        return new PageResponseResult(dto.getPage(),dto.getSize(),page.getTotal(),page.getRecords());
    }

    @Override
    public ResponseResult saveChannel(WmChannel channel) {

        if (channel==null||StringUtils.isEmpty(channel.getName())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName,channel.getName());
        int count = this.count(queryWrapper);

        //判断，若存在，提示存在；若不存在，保存
        if(count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        channel.setCreatedTime(new Date());
        this.save(channel);
        //返回频道id
        return ResponseResult.okResult(channel.getId());
    }
}
